<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\Community as CommunityModel;
use app\admin\model\UserRoseLog;
use app\admin\model\CommunityMessage;
use app\admin\model\CommunityLike;
use app\admin\model\Follow;

/**
 * 产品控制器
 */
class Community extends Api
{
    protected $noNeedLogin = ['community','communitydetail','getcommunitymessage'];

	public function _initialize(){
		$action = request()->action();
		$ignore = array('host','accept','content-length','content-type');
		$headers = array();
		if($this->request->request('token')){
			$headers['token'] = $this->request->request('token');
		}else{
			foreach($_SERVER as $key=>$value){
				if(substr($key, 0, 5)==='HTTP_'){
					$key = substr($key, 5);
					$key = str_replace('_', ' ', $key);
					$key = str_replace(' ', '-', $key);
					$key = strtolower($key);
					if(!in_array($key, $ignore)){
						$headers[$key] = $value;
					}
				}
			}
		}
		if(empty($headers['token']) && in_array($action,$this->noNeedLogin)){
			//当未传token并且控制器可不不传token情况下不需要验证登录
		}else{
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
			
	}
    
    
    
    //获取社区列表
    public function community(){
        $token = $this->request->request('token','');
        $orderby = $this->request->request('orderby',3);
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = [];
        if($orderby == 1){ //我的关注
            if($token){
                $user=User::where(array('token'=>$token))->find();
                $user_ids=Follow::where(['fans_user_id'=>$user['id']])->column('user_id');
                $user_ids[] = '439';
                $where = ['user_id'=>['in',$user_ids]];
            }else{
                $where = ['id'=>-1];
            }
            $order = 'add_time desc';
        }elseif($orderby == 3){ //精选
            $order = 'recommend_time desc';
        }elseif($orderby == 4){  //最新
            $order = 'add_time desc';
        }
        $list = CommunityModel::where(['status'=>1])
                ->where($where)
                ->order($order)
                ->limit(($page-1)*$pagesize,$pagesize)
                ->select();
        if($list){
            foreach ($list as &$v) {
                $v['user'] = User::where('id',$v['user_id'])->find();
                $v['add_time'] = timeago($v['add_time']);
                $rose_in=UserRoseLog::where(['user_id'=>$v['user_id'],'rose_money'=>array('gt',0),'type'=>['neq',18]])->sum('rose_money');
                $v['rose_level']=rose_level($rose_in);
                $v['imgArr'] = explode(',',$v['imgs']);
                $v['message_num'] = 0;
                $message = CommunityMessage::where(['community_id'=>$v['id'],'status'=>1])->order('add_time desc')->limit(0,2)->select();
                if($message){
                    if(count($message) == 2){
                        $arr = [$message[1],$message[0]];
                        $message = $arr;
                    }
                    // foreach ($message as $k=>&$vs) {
                    //     $arrPX1[$k] =  $vs['id'];
                    // }
                    // array_multisort($arrPX1, SORT_ASC, $message);

                    foreach ($message as $k=>&$vs) {
                        $vs['nickname'] = User::where(['id'=>$vs['user_id']])->value('nickname');
                        $vs['p_nickname'] = '';
                        if($vs['pid'] && $vs['p_user_id']){ //存在上级
                            $vs['p_nickname'] = User::where(['id'=>$vs['p_user_id']])->value('nickname');
                        }
                    }
                    $v['message_num'] = CommunityMessage::where(['community_id'=>$v['id'],'status'=>1])->count();
                }
                $v['message'] = $message;
                $v['like_num'] = CommunityLike::where(['community_id'=>$v['id']])->count();
                $like = CommunityLike::where(['community_id'=>$v['id'],'user_id'=>$this->user['id']])->find();
                $v['is_like'] = $like ? 1 : 0;

                $info = Follow::where(['fans_user_id'=>$this->user['id'],'user_id'=>$v['user_id']])->value('id');
                if($info){
                    $v['is_follow'] = 1;
                }else{
                    $v['is_follow'] = 0;
                }
            }
        }
        $this->success('获取成功',$list);
    }
    //获取社区详情
    public function communityDetail(){
        $id = $this->request->request('id','');
        $token = $this->request->request('token','');

        $v = CommunityModel::where(['id'=>$id])->find();
        $v['user'] = User::where('id',$v['user_id'])->find();
        $v['add_time'] = timeago($v['add_time']);
        $rose_in=UserRoseLog::where(['user_id'=>$v['user_id'],'rose_money'=>array('gt',0),'type'=>['neq',18]])->sum('rose_money');
        $v['rose_level']=rose_level($rose_in);
        $v['imgArr'] = explode(',',$v['imgs']);
        $v['message_num'] = 0;
        $message = CommunityMessage::where(['community_id'=>$v['id'],'status'=>1])->order('add_time desc')->limit(0,2)->select();
        if($message){
            foreach ($message as $k=>&$vs) {
                $vs['nickname'] = User::where(['id'=>$vs['user_id']])->value('nickname');
                $vs['p_nickname'] = '';
                if($vs['pid'] && $vs['p_user_id']){ //存在上级
                    $vs['p_nickname'] = User::where(['id'=>$vs['p_user_id']])->value('nickname');
                }
                $arrPX1[$k] =  $vs['id'];
            }
            $v['message_num'] = CommunityMessage::where(['community_id'=>$v['id'],'status'=>1])->count();

            array_multisort($arrPX1, SORT_ASC, $message);
        }
        $v['message'] = $message;
        $v['like_num'] = CommunityLike::where(['community_id'=>$v['id']])->count();
        $like = CommunityLike::where(['community_id'=>$v['id'],'user_id'=>$this->user['id']])->find();
        $v['is_like'] = $like ? 1 : 0;
        $user = [];
		if($token){
			$user=User::where(array('token'=>$token))->find();
		}
        $v['is_follow'] = 0;
        if($user){
            $follow=Follow::where(array('fans_user_id'=>$user['id'],'user_id'=>$v['id']))->find();
            $v['is_follow']=$follow?1:0;
        }
        $this->success('获取成功',$v);
    }

    //点赞操作
    public function setLike(){
        $community_id	= $this->request->request('community_id','');
        $info = CommunityLike::where(['community_id'=>$community_id,'user_id'=>$this->user['id']])->find();
        if($info){
            CommunityLike::where(['id'=>$info['id']])->delete();
        }else{
            CommunityLike::insert(['community_id'=>$community_id,'user_id'=>$this->user['id'],'add_time'=>time()]);
        }
        $this->success('操作成功');
    }

    //发布社区
    public function addCommunity(){
        $data['content']	= $this->request->request('content','');
        $data['imgs']	    = $this->request->request('imgs','');
        $data['status']     = $this->request->request('status',0);
        $data['user_id']		=	$this->user['id'];
        $data['add_time']		=	time();
        if(empty($data['content']) && empty($data['imgs'])){
            $this->error('请输入内容或添加图片');		
        }
        CommunityModel::insert($data);
        //查询今天是否已经发布成功过
        $redis = redis_init();
        $sb_time = $redis->get($this->user['id'].'CommunityModel');	
        if(!$sb_time){
            //第一次发布给奖励
            roseandlog($data['user_id'],1,22,'发布动态通过奖励');
            $redis->set($this->user['id'].'CommunityModel',time());
        }else{
            //判断发布时间
            $time1 = date('Y-m-d',$sb_time);
            $time2 = date('Y-m-d',time());
            if($time1 != $time2){
                //上次发布不是今天 给奖励
                roseandlog($data['user_id'],1,22,'发布动态通过奖励');
                $redis->set($this->user['id'].'CommunityModel',time());
            }
        }
        $this->success('发布成功');
    }

    //获取评论信息
    public function getCommunityMessage(){
        $community_id = $this->request->request('community_id');
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);

        $list = CommunityMessage::where(['community_id'=>$community_id,'status'=>1,'pid'=>0])->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();

        if($list){
            foreach ($list as &$v) {
                $user = User::field('nickname,avatar')->where(['id'=>$v['user_id']])->find();
                $v['add_time'] = date('m-d',$v['add_time']);
                $v['nickname'] = $user['nickname'];
                $v['avatar'] = $user['avatar'];
                $v['answers'] = '';
                $answers = CommunityMessage::where(['pid'=>$v['id'],'status'=>1])->order('add_time')->select();
                if($answers){
                    foreach ($answers as &$answer) {
                        $user = User::field('nickname,avatar')->where(['id'=>$answer['user_id']])->find();
                        $answer['nickname'] = $user['nickname'];
                        $answer['avatar'] = $user['avatar'];
                        if($answer['p_user_id']){ //存在上级
                            $answer['p_nickname'] = User::where(['id'=>$answer['p_user_id']])->value('nickname');
                        }
                    }
                   
                    $v['answers'] = $answers;
                }
            }
        }
        $this->success('获取成功',$list);
    }


    //评论信息
    public function addCommunityMessage(){
        $content = $this->request->request('content');//评论内容
        $pid = $this->request->request('pid',0);//上级id
        $p_user_id = $this->request->request('p_user_id',0);//上级user_id
        $community_id = $this->request->request('community_id');
        if(!$community_id){
            $this->error('内容已被删除,无法评论!');
        }
        if(!$content){
            $this->error('内容不能为空');
        }
        $arr = [
            'user_id'=>$this->user['id'],
            'community_id'=>$community_id,
            'pid'=>$pid,
            'p_user_id'=>$p_user_id,
            'content'=>$content,
            'add_time'=>time(),
        ];
        $arr['id'] = CommunityMessage::insertGetId($arr);
        if($arr['pid'] && $arr['p_user_id']){ //存在上级
            $arr['p_nickname'] = User::where(['id'=>$arr['p_user_id']])->value('nickname');
        }else{
            $arr['p_nickname'] = '';
        }
        $arr['add_time'] =  date('m-d',time());
        $this->success('评论成功',$arr);
    }

    //删除评论信息
    public function delCommunityMessage(){
        $id = $this->request->request('id');
        if(!$id){
            $this->error('参数错误!');
        }
        $arr = [
            'user_id'=>$this->user['id'],
            'id'=>$id,
            'status'=>1
        ];
        $res = CommunityMessage::where($arr)->find();
        if(!$res){
            $this->error('未查询到可删除评论!');
        }
        CommunityMessage::where($arr)->update(['status'=>-1]);
        $this->success('删除成功');
    }

}